import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Checkbox, Card, Spin, message, Table, Alert, Collapse} from 'antd';
import routes from './routes';
import {PAGE, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import PartCategorySelectPanel from './PartCategorySelectPanel';
import SearchInput from 'Shared/components/SearchInput';
import {conventEnumValueToString} from '../utils';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import InputAmount from '../common/InputAmount';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import {validateAdd, renderBoolean, validateEqual} from './utils';
import Return from '../common/Return';
import DutyUnit from '../common/DutyUnitSelect/SelectPanel';
import PWCSelectPanel from './PartWarrantyCategory/SelectEdit';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
import {dutyUnitType, dutyUnitStatus, baseDataStatus, currency, dealerType} from '../Enum';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
const {Panel} = Collapse;
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const dutyUnitCondition = {
    type: dutyUnitType.索赔供应商,
    status: dutyUnitStatus.生效
};
const flagOptions = [
    {
        text: renderBoolean(true),
        value: Number(true),
    },
    {
        text: renderBoolean(false),
        value: Number(false),
    },
];
export const dealerConditions = {
    type: dealerType.总代
};
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        showPartCategory: false
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };


    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };

    handleFlagChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, typeof value === 'number' ? Boolean(value) : value);
    };
    onSubmit = () => {
        const result = validateAdd(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result.msg);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };


    onClickAdd = () => {
        this.setState({
            hasOperat: true,
            showPanel: true
        });
    }

    onDelete = e => {
        const {id} = e.target.dataset;
        this.setState({
            hasOperat: true,
        });
        this.props.onDelete(id);
    }

    onDeleteAll = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAll();
    }

    onSelectDetails = (data = []) => {
        this.setState({showPanel: false});
        if(data.length)
            this.props.onSelectDetails(data);
    }

    onSelect = (data = {}, id) => {
        this.setState({
            hasOperat: true,
        });
        this.props.updateBrand({
            partWarrantyCategoryId: data.id,
            partWarrantyCategoryCode: data.code,
            partWarrantyCategoryName: data.name,
            id
        });
    }

    onChangeBox = e => {
        const {checked, id} = e.target;
        this.setState({
            hasOperat: true,
        });
        this.props.onChangeDetail(id, checked);
    }

    onDeletePrice = e => {
        const {id} = e.target.dataset;
        this.setState({
            hasOperat: true,
        });
        this.props.onDeletePrice(id);
    }

    onDeleteAllPrice = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAllPrice();
    }

    onUpdatePrices = (value, id) => {
        const {partServicePrices = []} = this.props.conditions;
        const partServicePrice = partServicePrices.find(v => v.id === id);
        const index = partServicePrices.findIndex(v => v.year === partServicePrice.year && v.month === partServicePrice.month &&
            v.currency === partServicePrice.currency && v.brandId === value);
        if(index === -1)
            this.props.updatePrice({
                brandId: value,
                id
            });
        else message.warn(this.props.intl.formatMessage({
            id: 'add.message.brandYearMonthCurrency',
            defaultMessage: '品牌,年份,月份,币种不能重复'
        }));
    };

    onDeleteBrand = e => {
        const {id} = e.target.dataset;
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteBrand(id);
    }

    onDeleteAllBrand = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAllBrand();
    }

    onUpdateBrand = (value, id) => {
        const {partServiceProperties = [], tempPartServiceProperties = []} = this.props.conditions;
        const partServicePropertiesList = partServiceProperties.concat(tempPartServiceProperties);
        const partServicePrice = partServiceProperties.find(v => v.id === id);
        const index = partServicePropertiesList.findIndex(v => v.dealerId === partServicePrice.dealerId && v.brandId === value);
        if(index === -1)
            this.props.updateBrand({
                brandId: value,
                id
            });
        else message.warn(this.props.intl.formatMessage({
            id: 'add.message.brandAndDealer',
            defaultMessage: '品牌和总代不能重复'
        }));
    };
    onSelectDealer = (data, id) => {
        const {partServiceProperties = [], tempPartServiceProperties = []} = this.props.conditions;
        const partServicePropertiesList = partServiceProperties.concat(tempPartServiceProperties);
        const partServiceProperty = partServiceProperties.find(v => v.id === id);
        const index = partServicePropertiesList.findIndex(v => v.brandId === partServiceProperty.brandId && v.dealerId === data.id);
        if(index === -1)
            this.props.updateBrand({
                dealerId: data.id,
                dealerCode: data.code,
                dealerName: data.name,
                id
            });
        else message.warn(this.props.intl.formatMessage({
            id: 'add.message.brandAndDealer',
            defaultMessage: '品牌和总代不能重复'
        }));
    };
    onUpdateCurrency= (value, id) => {
        const {partServicePrices = []} = this.props.conditions;
        const partServicePrice = partServicePrices.find(v => v.id === id);
        const index = partServicePrices.findIndex(v => v.year === partServicePrice.year && v.month === partServicePrice.month &&
            v.currency === value && v.brandId === partServicePrice.brandId);
        if(index === -1)
            this.props.updatePrice({
                currency: value,
                id
            });
        else message.warn(this.props.intl.formatMessage({
            id: 'add.message.brandYearMonthCurrency',
            defaultMessage: '品牌,年份,月份,币种不能重复'
        }));
    };


    onUpdatePrice = (value, id) => {
        this.props.updatePrice({
            price: value,
            id
        });
    };

    onUpdateAuthor = (value, id) => {
        this.props.updateBrand({
            isPreAuthorized: typeof value === 'number' ? Boolean(value) : value,
            id
        });
    }
    onUpdateNeedPicture = (value, id) => {
        this.props.updateBrand({
            isNeedPicture: typeof value === 'number' ? Boolean(value) : value,
            id
        });
    }
    onClickPartCategory = () => {
        this.setState({showPartCategory: true});
    };
    onClosePartCategory = () => {
        this.setState({showPartCategory: false});
    };
    onSelectPartCategory = data => {
        this.props.onConditionsChange('partCategoryId', data.id);
        this.props.onConditionsChange('partCategoryCode', data.code);
        this.props.onConditionsChange('partCategoryName', data.name);
        this.setState({
            showPartCategory: false
        });
    };
    onAddDetail = e => {
        e.stopPropagation();
        this.props.onAddDetail();
    }
    onClickMore = () => {
        this.props.onClickMoreDetail();
    }
    render() {
        const {partDutyUnits = [], partServiceProperties = [], partServicePrices = [], tempPartServiceProperties = []} = this.props.conditions;
        const currentSelectRowKeys = partDutyUnits.map(item => item.dutyUnitId);
        
        const propertyColums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.brandId',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandId',
                className: styles.minWidth,
                render: (text, record) => {
                    const isEquel = validateEqual(record, partServiceProperties.concat(tempPartServiceProperties));
                    const validate = (!text || isEquel) && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <WrappedSelect
                                id={record.id}
                                value={text}
                                options={this.props.brands}
                                onChange={this.onUpdateBrand} />
                        </FormItem>
                    );
                }
            }, {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.dealerId',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerId',
                className: styles.minWidth,
                render: (text, record) => {
                    const isEquel = validateEqual(record, partServiceProperties.concat(tempPartServiceProperties));
                    const validate = (!text || isEquel) && this.state.isValidate ? {validateStatus: 'error'} : null;
                    const dealerInfo = record.dealerId ? {
                        id: record.dealerId,
                        code: record.dealerCode,
                        name: record.dealerName
                    } : null;
                    return (
                        <FormItem {...validate} required>
                            <DealerSelectPanel
                                allowClear={false}
                                value={dealerInfo}
                                conditions={dealerConditions}
                                onSelect={data => this.onSelectDealer(data, record.id)} />
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.partWarrantyCategoryId',
                    defaultMessage: '索赔分类标准'
                }),
                dataIndex: 'partWarrantyCategory',
                className: styles.minWidth,
                render: (text, record) => {
                    const validate = !record.partWarrantyCategoryId && this.state.isValidate ? {validateStatus: 'error'} : null;

                    const pwcInfo = record.partWarrantyCategoryId ? {
                        id: record.partWarrantyCategoryId,
                        code: record.partWarrantyCategoryCode,
                        name: record.partWarrantyCategoryName
                    } : null;
                    return (
                        <FormItem {...validate} required>
                            {record.dealerCode ? <PWCSelectPanel
                                value={pwcInfo}
                                id={record.id}
                                dealerId={record.dealerId}
                                allowClear={false}
                                onSelect={this.onSelect} /> : <TextInput name="dealerId"
                                value={''} disabled placeholder={this.props.intl.formatMessage({
                                    id: 'add.dealerComp.placeholder',
                                    defaultMessage: '请先选择总代'
                                })} />}
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.isPreAuthorized',
                    defaultMessage: '是否预授权'
                }),
                dataIndex: 'isPreAuthorized',
                className: styles.minWidth,
                render: (text, record) => {
                    const validate = typeof record.isPreAuthorized !== 'boolean' && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <WrappedSelect
                                id={record.id}
                                value={typeof record.isPreAuthorized === 'boolean' ? Number(record.isPreAuthorized) : record.isPreAuthorized}
                                options={flagOptions}
                                onChange={this.onUpdateAuthor} />
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.isNeedPicture',
                    defaultMessage: '是否需要索赔图片'
                }),
                dataIndex: 'isNeedPicture',
                className: styles.minWidth,
                render: (text, record) => {
                    const validate = typeof record.isNeedPicture !== 'boolean' && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <WrappedSelect
                                id={record.id}
                                value={typeof record.isNeedPicture === 'boolean' ? Number(record.isNeedPicture) : record.isNeedPicture}
                                options={flagOptions}
                                onChange={this.onUpdateNeedPicture} />
                        </FormItem>
                    );
                }
            },
            {
                title: partServicePrices.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAllBrand}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDeleteBrand} key="delete" data-id={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        const priceColums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.brandId',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandId',
                className: styles.minWidth,
                render: (text, record) => {
                    const isEquel = validateEqual(record, partServicePrices);
                    const validate = (!text || isEquel) && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <WrappedSelect
                                id={record.id}
                                value={text}
                                options={this.props.brands}
                                onChange={this.onUpdatePrices} />
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.year',
                    defaultMessage: '年份'
                }),
                dataIndex: 'year',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.month',
                    defaultMessage: '月份'
                }),
                dataIndex: 'month',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                className: styles.minWidth,
                render: (text, record) => {
                    const validate = !text && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <WrappedSelect
                                id={record.id}
                                value={text}
                                options={currency.toList(language)}
                                onChange={this.onUpdateCurrency} />
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.priceColums.price',
                    defaultMessage: '价格'
                }),
                dataIndex: 'price',
                className: styles.minWidth,
                render: (text, record) => {
                    const validate = !text && this.state.isValidate ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate} required>
                            <InputAmount
                                min={0}
                                id={record.id}
                                value={text}
                                onBlur={this.onUpdatePrice} />
                        </FormItem>
                    );
                }
            },
            {
                title: partServicePrices.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAllPrice}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDeletePrice} key="delete" data-id={record.id}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.dutyUnitCode',
                    defaultMessage: '责任单位编号'
                }),
                dataIndex: 'dutyUnitCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.dutyUnitName',
                    defaultMessage: '责任单位名称'
                }),
                dataIndex: 'dutyUnitName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.isDefault',
                    defaultMessage: '是否首选项'
                }),
                dataIndex: 'isCaused',
                render: (text, record) => (
                    <FormItem>
                        <Checkbox id={record.dutyUnitId} checked={record.isDefault} onChange={this.onChangeBox} />
                    </FormItem>
                )
            },
            {
                title: partDutyUnits.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDelete} key="delete" data-id={record.dutyUnitId}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.claimModal.title',
                        defaultMessage: '责任单位查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <DutyUnit
                        multi
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.onSelectDetails}
                        conditions={dutyUnitCondition} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Collapse className={styles.collapseMarginTop}>
                            <Panel header={<div><DescriptionList className={styles.desList}>
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.code',
                                        defaultMessage: '备件编号'
                                    })}>
                                    {this.props.conditions.code}
                                </Description>
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.name',
                                        defaultMessage: '备件名称'
                                    })}>
                                    {this.props.conditions.name}
                                </Description>
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.description',
                                        defaultMessage: '英文描述'
                                    })}>
                                    {this.props.conditions.description}
                                </Description>
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.partReplacementCode',
                                        defaultMessage: '替代件编号'
                                    })}>
                                    {this.props.conditions.partReplacementCode}
                                </Description>
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.supplierCode',
                                        defaultMessage: '首选供应商代码'
                                    })}>
                                    {this.props.conditions.supplierCode &&
                                        this.props.conditions.supplierCode.length > 30
                                        ? <Ellipsis tooltip fullWidthRecognition length={30}>
                                            {this.props.conditions.supplierCode}</Ellipsis>
                                        : this.props.conditions.supplierCode}
                                </Description>
                            </DescriptionList>
                            <DescriptionList className={styles.desList} col={1} size="large">
                                <Description
                                    term={this.props.intl.formatMessage({
                                        id: 'detail.info.productCategoryCode',
                                        defaultMessage: '车型编号'
                                    })}>
                                    {this.props.conditions.productCategoryCode}
                                </Description>
                            </DescriptionList>
                            <DescriptionList className={styles.desList} col={1} size="large">
                                <Description term={this.props.intl.formatMessage({
                                    id: 'detail.info.remark',
                                    defaultMessage: '备注'
                                })}>
                                    {this.props.conditions.remark}
                                </Description>
                            </DescriptionList></div>}>
                                <DescriptionList>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.length',
                                            defaultMessage: '备件长度（mm）'
                                        })}>
                                        {this.props.conditions.length}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.width',
                                            defaultMessage: '备件宽度（mm）'
                                        })}>
                                        {this.props.conditions.width}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.height',
                                            defaultMessage: '备件高度（mm）'
                                        })}>
                                        {this.props.conditions.height}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.netWeight',
                                            defaultMessage: '备件净重（kg）'
                                        })}>
                                        {this.props.conditions.netWeight}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.grossWeight',
                                            defaultMessage: '备件毛重（kg）'
                                        })}>
                                        {this.props.conditions.grossWeight}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.alternativePlan',
                                            defaultMessage: '替代方案'
                                        })}>
                                        {this.props.conditions.alternativePlan}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'add.info.partCategory',
                                            defaultMessage: '备件分类'
                                        })}>
                                        <SearchInput
                                            disabled={true}
                                            className={styles.detail}
                                            value={this.props.conditions.partCategoryId ? `(${this.props.conditions.partCategoryCode}) ${this.props.conditions.partCategoryName}` : ''}
                                            id={this.props.conditions.partCategoryId}
                                            onClickSearchBtn={this.onClickPartCategory} />
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.unit',
                                            defaultMessage: '计量单位'
                                        })}>
                                        {this.props.conditions.unit}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.certificationMark',
                                            defaultMessage: '认证标识'
                                        })}>
                                        {this.props.conditions.certificationMark}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.minPackSize',
                                            defaultMessage: '最小包装数'
                                        })}>
                                        {this.props.conditions.minPackSize}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.minOrderQuantity',
                                            defaultMessage: '最小订购量'
                                        })}>
                                        {this.props.conditions.minOrderQuantity}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.usagePerCar',
                                            defaultMessage: '每车用量'
                                        })}>
                                        {this.props.conditions.usagePerCar}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.isConsume',
                                            defaultMessage: '是否消耗库存'
                                        })}>
                                        {this.props.conditions.isConsume}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.isDecimalAllowed',
                                            defaultMessage: '是否允许小数'
                                        })}>
                                        {renderBoolean(this.props.conditions.isDecimalAllowed)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.overseaOnly',
                                            defaultMessage: '是否海外专用'
                                        })}>
                                        {renderBoolean(this.props.conditions.overseaOnly)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.shelfLife',
                                            defaultMessage: '保质期'
                                        })}>
                                        {this.props.conditions.shelfLife}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.safeMaterial',
                                            defaultMessage: '安全件'
                                        })}>
                                        {this.props.conditions.safeMaterial}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.packageRule',
                                            defaultMessage: '包装规则'
                                        })}>
                                        {this.props.conditions.packageRule}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.isImported',
                                            defaultMessage: '是否进口件'
                                        })}>
                                        {renderBoolean(this.props.conditions.isImported)}
                                    </Description>
                                    <Description
                                        term={this.props.intl.formatMessage({
                                            id: 'detail.info.status',
                                            defaultMessage: '状态'
                                        })}>
                                        {conventEnumValueToString(baseDataStatus, this.props.conditions.status)}
                                    </Description>
                                </DescriptionList>
                            </Panel>
                            <Panel header={this.props.intl.formatMessage({
                                id: 'queryPanel.price.partServiceProperties',
                                defaultMessage: '品牌服务信息'
                            })}
                            extra={<Button onClick={this.onAddDetail} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>}>
                                <Table
                                    className="white-space-nowrap"
                                    columns={propertyColums}
                                    rowKey="id"
                                    pagination={false}
                                    dataSource={partServiceProperties}
                                    {...TABLE} />
                                {tempPartServiceProperties.length > 0 && <div
                                    className={styles.moreButton}>
                                    <Button onClick={this.onClickMore}>{this.props.intl.formatMessage({
                                        id: 'add.button.loadingMore',
                                        defaultMessage: 'loading more'
                                    })}</Button>
                                </div>}
                            </Panel>
                        </Collapse>
                        <Card
                            extra={<Button onClick={this.props.onAddPriceDetail} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>}
                            title={this.props.intl.formatMessage({
                                id: 'queryPanel.price.partServicePrices',
                                defaultMessage: '价格信息'
                            })}>
                            <Alert className={styles.divider} type="info" message={this.props.intl.formatMessage({
                                id: 'queryPanel.alert.message',
                                defaultMessage: '当前可新增，编辑的价格为当前月份索赔时，直接使用的索赔价格'
                            })} showIcon />
                            <Table
                                className="white-space-nowrap"
                                columns={priceColums}
                                rowKey="id"
                                pagination={false}
                                dataSource={partServicePrices}
                                {...TABLE} />
                        </Card>
                        <Card
                            extra={<Button onClick={this.onClickAdd} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>}
                            title={this.props.intl.formatMessage({
                                id: 'add.table.partDutyUnits',
                                defaultMessage: '备件与责任单位关系清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="dutyUnitId"
                                pagination={false}
                                dataSource={partDutyUnits}
                                {...TABLE} />
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                {
                    this.state.showPartCategory &&
                        <PartCategorySelectPanel
                            selectKey={this.state.partCategoryId}
                            onCancel={this.onClosePartCategory}
                            onSelect={this.onSelectPartCategory} />
                }
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onDelete: PropTypes.func.isRequired,
    onDeleteAll: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    onSelectDetails: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickUpdateInfo,
    deleteDetail,
    deleteAllDetail,
    selectData,
    selectDetails,
    changeDefault,
    getEditInit,
    deletePriceDetail,
    deleteAllPrice,
    addPrice,
    updatePrice,
    addBrand,
    updateBrand,
    deleteBrandDetail,
    deleteAllBrand,
    moreDetail
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.update) && options.includes(PERMISSION.update);
    }
);
const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        }));
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrandsData(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onClickUpdateInfo(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.goBack();
    },
    onUmount: () => dispatch(clearData()),
    onDelete: id => dispatch(deleteDetail(id)),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onSelectDetails: data => dispatch(selectDetails(data)),
    onSelect: data => dispatch(selectData(data)),
    onChangeDetail: (id, value) => dispatch(changeDefault(id, value)),
    onDeletePrice: id => dispatch(deletePriceDetail(id)),
    onDeleteAllPrice: () => dispatch(deleteAllPrice()),
    onAddDetail: () => dispatch(addBrand()),
    updateBrand: data => dispatch(updateBrand(data)),
    onAddPriceDetail: () => dispatch(addPrice()),
    updatePrice: data => dispatch(updatePrice(data)),
    onDeleteBrand: id => dispatch(deleteBrandDetail(id)),
    onDeleteAllBrand: () => dispatch(deleteAllBrand()),
    onClickMoreDetail: () => dispatch(moreDetail())
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
